# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: fengyang, donggu

import datetime
import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
from coin.exchange.ftx_futures.kr_rest.contract_util import find_contract_type_from_expiry
import re

asset_multiplier_base_list = ["10000NFT", "1000BONK", "1000BTT", "1000LUNC", "1000XEC", "SHIB1000", "1000FLOKI", "1000PEPE", "10000LADYS"]


def generate():
  mea = 'Futures.Bybit.v2-linear'
  me = 'Futures.Bybit'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://api.bybit.com/v2/public/symbols").json()['result']

  pis = []
  for info in data:
    if 'USDT' != info['quote_currency']:
      continue
    native_symbol = info['name']
    alias = info['alias']
    native_base = info['base_currency']
    native_quote = info['quote_currency']
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)

    base_quote = '%s%s' % (native_base, native_quote)
    if alias == base_quote:
      symbol = "%s-%s.PERPETUAL" % (base, quote)
    else:
      if alias.startswith(base_quote):
        month_day = alias[len(base_quote):]
        current_month_day = "%02d%02d" % (
            int(datetime.date.today().month), int(datetime.date.today().day))
        year = datetime.date.today().year
        if int(current_month_day) > int(month_day):
          year += 1
        year_month_day = '%s%s' % (year, month_day)
        expiry_datetime = datetime.datetime.strptime(year_month_day, '%Y%m%d')
        try:
          contract_type = find_contract_type_from_expiry(datetime.datetime.now(), expiry_datetime)
        except ValueError:
          # Next next quarter case?
          continue
        if contract_type == 'quarter':
          symbol = "%s-%s.QUARTER" % (base, quote)
        elif contract_type == 'next_quarter':
          symbol = "%s-%s.NEXT_QUARTER" % (base, quote)
        else:
          # Ignore next next quarter.
          continue
      else:
        raise ValueError(alias)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=float(info['price_filter']['tick_size']),
        qty_ticksize=float(info['lot_size_filter']['qty_step']),
        contract_value=float(1),
        is_inverse=quote == 'USD',
    )

    if base in asset_multiplier_base_list:
      regex = "[0-9]{3,}"
      result = re.search(regex, base)
      asset_multiplier = float(result.group(0))
      if result.start() == 0:
        asset = base[len(result.group(0)):]
      else:
        asset = base[:result.start()]
      pi["asset_multiplier"] = asset_multiplier
      pi["asset"] = asset

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  base_currency_list = [info['native_base'] for info in data]
  quote_currency_list = [info['native_quote'] for info in data]
  balance_currency_list = [
      info['native_base'] for info in data if info['quote'] == 'USD'] + ['USDT']
  inverse_symbol_list = [
      info['native_symbol'] for info in data if info['quote'] == 'USD']
  usdt_symbol_list = [
      info['native_symbol'] for info in data if info['quote'] == 'USDT']
  res = {
      'base_currency_list': list(set(base_currency_list)),
      'quote_currency_list': list(set(quote_currency_list)),
      'balance_currency_list': list(set(balance_currency_list)),
      'inverse_symbol_list': list(set(inverse_symbol_list)),
      'usdt_symbol_list': list(set(usdt_symbol_list)),
  }
  return res


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
